Showing posts with label Spring Framework. Show all posts
Showing posts with label Spring Framework. Show all posts

Wednesday, January 23, 2008

Aspect Oriented Programming-Spring AOP

In continuation of the series of articles on Spring Framework,today lets explore the possibilities and solutions that can be achieved by using Aspect Oriented Programming,AOP and in particular Spring AOP.To start with I would like to delve upon core concepts related to AOP ,the myths and realities surrounding it,benefits over OOP(Object Oriented Programming) and the areas where it can be used effectively.

History of AOP?
object-oriented programming (OOP) introduced the concept of the object, which initiated a new way to structure applications and write programs. The same idea applies to the concept of the aspect.In 1996, Gregor Kiczales and his team at the Palo Alto Research Center (PARC), a subsidiary of Xerox Corporation that is located in California, originally defined the concept of the aspect.
Definition of aspect
An aspect is a common feature that's typically scattered across methods, classes, object hierarchies, or even entire object models. It is behavior that looks and smells like it should have structure, but you can't find a way to express this structure in code with traditional object-oriented techniques

AOP vs OOP
The aim behind the development of OOP was to organize the data of an
application and its associated processing into coherent entities. Doing so was achieved by having objects that encapsulate data along with the methods that manipulate the data and carry out the processing.From a conceptual point of view, an application is broken down according to the realworld objects that it models. In a stock-management application, for example, you might find
supplier, article, customer, and other types of objects.By grouping together all the objects that possess the same characteristics, the concept of a class complements the concept of the object.
OOP has undeniably improved software engineering.Developers have built more-complex programs in a simpler fashion than would have been possible through procedural programming. Furthermore, developers have written large applications in object-oriented languages. For example, the Java 2 Platform, Enterprise Edition (J2EE) application servers were programmed in the Java language. Similarly, developers have implemented complex class hierarchies to construct graphical user interfaces. The Swing API,included in Java 2 Platform, Standard Edition (J2SE), falls into this category.AOP simply adds new concepts that allow you to improve object-oriented applications by making them more modular. In addition, AOP streamlines the development process by allowing the separation of development tasks. For example, highly technical functionalities, such as security.AOP allows us to dynamically modify our static model to include the code required to fulfill the secondary requirements without having to modify the original static model

Benefits over OOP

Writing clear and elegant programs using only OOP is impossible in at least two cases when the application contains crosscutting functionalities, and when the application includes code scattering.Let us explore a bit on these limitations.

Cross-cutting concerns
While organizing an application into classes,the analysis must be driven by the need for separating and encapsulating the data and its associated processing into coherent entities.Although the classes are programmed independently of one another, they are sometimes behaviorally interdependent. Typically, this is the case when you implement rules of referential integrity. For example, a customer object must not be deleted while an outstanding order remains unpaid; otherwise, the program risks losing the contact details for that customer. To enforce this rule, you could modify the customer-deletion method so that it initially determines whether all the orders have been paid. However, this solution is deficient for several reasons:• Determining whether an order has been paid does not belong to customer management but to order management. Therefore, the customer class should not have to manage this
functionality. The customer class should not need to be aware of all the data-integrity rules that other classes in the application impose. Modifying the customer class to take these data-integrity rules into account restricts the possibilities of reusing the class in other situations. In other words, once the customer class implements any functionality that is linked to a different class, customer is no longer independently reusable, in many cases. Despite the fact that the customer class is not the ideal place to implement this referential-integrity rule, many object-oriented programs work this way for lack of a better solution. You might be thinking about integrating this functionality into an order class instead,but this solution is no better. No reason exists for the order class to allow the deletion of a customer. Strictly speaking, this rule is linked to neither the customers nor the orders but cuts across these two types of entities.One of the aims of dividing the data into classes is making the classes independent from one another. However, crosscutting functionalities, such as the rules of referential integrity,appear superimposed on the division—violating the independence of the classes. In other words, OOP does not allow you to neatly implement crosscutting functionalities.

Code-Scattering
In OOP, the principal way that objects interact is by invoking methods. In other words, an object that needs to carry out an action invokes a method that belongs to another object. (An object can also invoke one of its own methods.) OOP always entail two roles: that of the invoker and that of the invoked.When you write the code to call a method, you do not need to worry about how the service is implemented because the call interacts only with the interface of the invoked object. You need only ensure that the parameters in the call correspond to those of the method’s signature.Because methods are implemented within classes, you write each method as a block of code that is clearly delimited. To change a method, you obviously modify the file that contains the class where the method is defined. If you alter just the body of the method, the modification is transparent because the method will still be called in exactly the same way.However, if you change the method’s signature (for example, by adding a parameter),further implications arise. You must then modify all the calls to the method, hence you must modify any classes that invoke the method. If these calls exist in several places in the program,
making the changes can be extremely time-consuming.The main point is this: Even though the implementation of a method is located in a single class, the calls to that method can be scattered throughout the application. This phenomenon of code scattering slows down maintenance tasks and makes it difficult for object-oriented applications to adapt and evolve.

Ofcourse we can use design patterns like Observer & Decorator in OOP to handle such scenerios like cross-cutting concerns and code scattering.And the advantages associated by implementing them are enhanced modularity of the code and effective testing.In general Aspects are used to implement functionalities (security, persistence, logging, and so on) within an application.An aspect allows you to integrate crosscutting functionalities and code scattering into an object-oriented application by using the new concepts of the pointcut, the joinpoint, and the advice.

Pointcut
Its the point of execution in the application at which cross-cutting concern needs to be applied.
In aspect-oriented computer programming, a pointcut is a set of join points. Whenever the program execution reaches one of the join points described in the pointcut, a piece of code associated with the pointcut (called advice) is executed. This allows a programmer to describe where and when additional code should be executed in addition to an already defined behavior. This permits the addition of aspects to existing software, or the design of software with a clear separation of concerns, wherein the programmer weaves (merges) different aspects into a complete application. In Spring the a pointcut is just a set of methods that, when called, should have advices invoked around them. This is the second important pieces of a Spring AOP aspect implementation!

Join Points
A join point is a point in the control flow of a program. In aspect-oriented programming a set of join points is described as a pointcut. A join point is where the main program and the aspect meet(such as field access, method invocation , constructor invocation, etc.). Spring's built-in AOP only supports method invocation currently.

Advice
In aspect and functional programming, advice describes a class of functions which modify other functions when the latter are run; it is a certain function, method or procedure that is to be applied at a given join point of a program.

Here is the example ,The aspect ibelow parodies the traditional "Hello World" for AspectJ by providing an aspect that captures all calls to the void foo(int, String) method in the MyClass class.

A simple HelloWorld aspect in AspectJ

public aspect HelloWorld
{
pointcut callPointcut( ) :
call(void foo(int, String));
before( ) : callPointcut( )
{
System.out.println(
"Hello World");
System.out.println(
"In the advice attached to the call pointcut");
}
}

OK having understood the history behind AOP and the terminology associated with it,lets explore the subject for today,Spring AOP

AOP basics

  • Aspect: A modularized implementation of a software concern that cuts across various objects in a software implementation. Logging is a good example of an aspect. In Spring AOP, aspects are nothing more than regular Spring beans, which themselves are plain-old Java objects (POJO) registered suitably with the Spring Inversion of Control container. The core advantage in using Spring AOP is its ability to realize the aspect as a plain Java class.

  • Join point: A point during program execution, such as a method executing or an exception being handled. In Spring AOP, a join point exclusively pertains to method execution only, which could be viewed as a limitation of Spring AOP. However, in reality, it is enough to handle most common cases of implementing crosscutting concerns.

  • Advice: Information about "when" an aspect is to be executed with respect to the join point. Examples of types of advice are "around," "before," and "after." They specify when the aspect's code will execute with respect to a particular join point.

  • Pointcut: A declarative condition that identifies the join points for consideration during an execution run. Pointcut is specified as an expression. Spring AOP uses the AspectJ pointcut expression syntax. An example pointcut expression is: execution(* com.myorg.springaop.examples.MyService*.*(..)). Asterisks in the expression refer to wildcards, as is conventiona

Spring AOP

The Spring Framework integrates with more powerful AOP frameworks, such as AspectJ .To use Spring AOP, you need to implement cross-cutting concerns and configure those concerns
in your applications.Any advice written for Spring AOP is configurable in the Spring container through a simple, consistent configuration. This configuration is an important aspect of using AOP in Spring because it is the only one you need to remember for creating extension points to existing classes.For further understanding I recommend reading the following articles ,instead of me touching upon the Spring AOP concepts here again,as anyways they are self-explanatory.

Spring AOP

Implementing Spring AOP in Enterprise Applications

Implementing Cross Cutting concerns using Spring 2.0 AOP

Implementing Logging as an Aspect using Spring AOP Framework

Suggested Video Tutorial by Ramnivas Laddad on AOP(Author of AspectJ in Action)

GoogleTech Talks Video by Gregor Kiczales,who introduced Aspects



Monday, January 21, 2008

Transaction Management using Spring Framework

In the previous article of this series related to Spring Framework,we discussed how easy it is to Unit Test the POJOs in Spring and as well little introduction on how effective is Spring in implementing Transaction Management .In continuation of that article,today we will explore more about configuring Transaction Management in Spring for different datasources

Transaction Management in Spring

Sometimes the fundamental error in judgement a Java Developer makes when dealing with transactions are using global transactions instead of local transactions.First let us understand these two types of transactions.

What is a transaction ?
A database transaction is a unit of interaction with a database management system or similar system that is treated in a coherent and reliable way independent of other transactions. In general, a database transaction must be atomic, meaning that it must be either entirely completed or aborted. Ideally, a database system will guarantee the properties of Atomicity, Consistency, Isolation and Durability (ACID) for each transaction.

Purpose of Transaction

In database products the ability to handle transactions allows the user to ensure that integrity of a database is maintained.

A single transaction might require several queries, each reading and/or writing information in the database. When this happens it is usually important to be sure that the database is not left with only some of the queries carried out. For example, when doing a money transfer, if the money was debited from one account, it is important that it also be credited to the depositing account. Also, transactions should not interfere with each other. For more information about desirable transaction properties, see ACID.

In order to reflect the correct state of reality in the system, a transaction should have the following properties.

  • Atomicity: This is the all-or-nothing property. Either the entire sequence of operations is successful or unsuccessful. A transaction should be treated as a single unit of operation. Completed transactions are only committed and incomplete transactions are rolled back or restored to the state where it started. There is absolutely no possibility of partial work being committed.
  • Consistency: A transaction maps one consistent state of the resources (e.g. database) to another. Consistency is concerned with correctly reflecting the reality of the state of the resources. Some of the concrete examples of consistency are referential integrity of the database, unique primary keys in tables etc.
  • Isolation: A transaction should not reveal its results to other concurrent transactions before it commits. Isolation assures that transactions do not access data that is being concurrently updated. The other name for isolation is serialization.
  • Durability: Results of completed transactions have to be made permanent and cannot be erased from the database due to system failure. Resource managers ensure that the results of a transaction are not altered due to system failures.

A simple transaction is usually issued to the database system in a language like SQL in this form:

  1. Begin the transaction
  2. Execute several queries (although any updates to the database aren't actually visible to the outside world yet)
  3. Commit the transaction (updates become visible if the transaction is successful)

If one of the queries fails the database system may rollback either the entire transaction or just the failed query. This behaviour is dependent on the DBMS in use and how it is set up. The transaction can also be rolled back manually at any time before the commit.

Local vs Global Transactions
Local transactions are specific to a single transactional resource (a JDBC connection, for example), whereas global transactions are managed by the container and can span multiple transactional resources.

Unlike a centralized computing environment where application components and resources are located at a single site, and transaction management only involves a local data manager running on a single machine, in a distributed computing environment all the resources are distributed across multiple systems. In such a case transaction management needs to be done both at local and global levels. A local transaction is one which involves activities in a single local resource manager. A distributed or a global transaction is executed across multiple systems, and its execution requires coordination between the global transaction management system and all the local data managers of all the involved systems. The Resource Manager and Transaction Manager (TM), also known as a transaction processing monitor (TP monitor), are the two primary elements of any transactional system. In centralized systems, both the TP monitor and the resource manager are integrated into the DBMS server. To support advanced functionalities required in a distributed component-based system, separation of TP monitor from the resource managers is required.

Local transactions are easy to manage, and because most operations work with just one transactional resource (such as a JDBC transaction), using local transactions is enough. However, if you are not using Spring, you still have a lot of transaction management code to write, and if in the future the scope of the transaction needs to be extended across multiple transactional resources, you have to drop the local transaction management code and rewrite it to use global transactions.

A global or distributed transaction consists of several subtransactions and is treated as a single recoverable atomic unit. The global transaction manager is responsible for managing distributed transactions by coordinating with different resource managers to access data at several different systems. Since multiple application components and resources participate in a transaction, it's necessary for the transaction manager to establish and maintain the state of the transaction as it occurs.Global transactions in non-Spring application are, in most cases, coded using JTA, which is a complex API that depends on JNDI. This means that you have to use a J2EE application server

Two-Phase Commit (2PC) Protocol

The two-phase commit protocol enables the Atomicity in a distributed transaction scenario. The system module responsible for this protocol is usually called a transaction manager or a coordinator. As the name implies, there are two phases to the protocol. In the first phase, the coordinator asks each participant to vote on a commit or a rollback. This is accomplished by sending a so-called prepare request to each participant. When a participant votes for a commit, it loses its right to roll back independently, meaning that it has to wait for the final outcome received from the coordinator. The first phase ends when the coordinator receives all votes or if a timeout occurs. The second phase starts with the final decision made by the coordinator. In the case of a timeout or at least one "rollback" vote, the decision to roll back is sent to each participant that voted for "commit" in the first phase. As a result, all data modifications at all places involved are rolled back. Should all participants vote to commit, then and only then, the coordinator decides to perform a global commit and sends a commit notification to all participants. Consequently, all the work at all places is committed.

The complexity of the two-phase commit relates not only to the distributed nature of a transaction, but also to a possible non-atomic outcome of a transaction, i.e. heuristics. For example, the first participant may commit changes during phase two, while the second participant encounters a hardware failure when saving changes to the disk. Being able to roll back or at least notify the errors to recover the system into the original state is an important part of the process.

By persisting intermediate steps of the 2PC, that is, logging abort, ready to commit, and commit messages, the protocol provides a certain degree of reliability in case the coordinator or participants fail in the midst of transaction processing. The two-phase commit protocol can be implemented in a synchronous or asynchronous manner with variations to its actual execution.

Programmatic vs Declarative Transactions
The Java EE container implements support for transactions and facilitates the ACID properties required by the application logic. The container provides an implementation for the two-phase commit protocol between a transaction manager and underlying resources such as the database or messaging provider. The Java EE container is also responsible for the transaction context propagation and provides support for a distributed two-phase commit. With a distributed two-phase commit, a Java EE application can modify data across multiple application servers as if it is a single transaction.

The decision for whether to use programmatic or declarative transaction support depends on the level of transaction control and complexity required by the application design. With the declarative transaction support boundaries and individual properties of a transaction are specified in a deployment descriptor . With programmatic support to a transaction application logic encapsulates transactional characteristics in the code. A POJO object has to use the programmatic transaction demarcation. And because of Spring's Inversion of Control and dependency injection CMT is now also available for POJO applications.

Container-Managed Transactions(EJB 2.1) vs. Spring’s Declarative Transaction management(Spring 1.2):

EJB’s Transaction attribute:
Required
RequiresNew
Mandatory
NotSupported
Supports
Never

Spring’s Progagation behavior:
Interface org.springframework.transaction.TransactionDefinition
PROPAGATION_MANDATORY
PROPAGATION_NESTED
PROPAGATION_NEVER
PROPAGATION_NOT_SUPPORTED
PROPAGATION_REQUIRED
PROPAGATION_REQUIRES_NEW
PROPAGATION_SUPPORTS

(b)
EJB’s Isolation level:
Interface java.sql.Connection
TRANSACTION_NONE
TRANSACTION_READ_COMMITTED
TRANSACTION_READ_UNCOMMITTED
TRANSACTION_REPEATABLE_READ
TRANSACTION_SERIALIZABLE

Spring’s Isolation level:
Interface org.springframework.transaction.TransactionDefinition
ISOLATION_DEFAULT
ISOLATION_READ_COMMITTED
ISOLATION_READ_UNCOMMITTED
ISOLATION_REPEATABLE_READ
ISOLATION_SERIALIZABLE

(c)
Rolling Back a Container-Managed Transaction
There are two ways to roll back a container-managed transaction.
First, if a system exception is thrown, the container will automatically roll back the transaction. Second, by invoking the setRollbackOnly method of the EJBContext interface, the bean method instructs the container to roll back the transaction. If the bean throws an application exception, the rollback is not automatic but can be initiated by a call to setRollbackOnly.

Spring’s Roll back rules
Transaction can be declared to roll back or not based on exceptions that are thrown during the course of the transaction.
By default, transactions are rolled back only on runtime exceptions and not on checked exceptions.

Bean-Managed Transactions(EJB 2.1) vs. Spring’s Programmatic Transaction management(Spring 1.2):
In a bean-managed transaction, the code in the session or message-driven bean explicitly marks the boundaries of the transaction. An entity bean cannot have bean-managed transactions; it must use container-managed transactions instead.
Although beans with container-managed transactions require less coding, they have one limitation: When a method is executing, it can be associated with either a single transaction or no transaction at all. If this limitation will make coding your bean difficult, you should consider using bean-managed transactions.

Spring provides two means of programmatic transaction management:
Using the TransactionTemplate
Using a PlatformTransactionManager implementation directly

Configuration of Deployment Descriptor-Spring vs EJB

ejb-jar.xml

<ejb-jar>
<enterprise-beans>
<!– A minimal session EJB deployment –>
<session>
<ejb-name>PostingEJB</ejb-name>
<home>ejbs.PostingHome</home>
<remote>ejbs.Posting</remote>
<ejb-class>ejbs.PostingBean</ejb-class>
<!– or Stateless –>
<session-type>Stateful</session-type>
<transaction-type>Container</transaction-type>
</session>

<!– OPTIONAL, can be many. How the container is to manage
transactions when calling anEJB’s business methods –>
<container-transaction>
<!– Can specify many methods at once here –>
<method>
<ejb-name>EmployeeRecord</ejb-name>
<method-name>*</method-name>
</method>
<!– NotSupported|Supports|Required|RequiresNew|Mandatory|Never –>
<trans-attribute>Required</trans-attribute>
</container-transaction>

<container-transaction>
<method>
<ejb-name>Payroll</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>

Spring applicationcontext.xml

<beans>
<bean id=”petStore”
class=”org.springframework.transaction.interceptor.TransactionProxyFactoryBean”>
<property name=”transactionManager” ref=”txManager”/>
<property name=”target” ref=”petStoreTarget”/>
<property name=”transactionAttributes”>
<props>
<prop key=”insert*”>
PROPAGATION_REQUIRED,-MyCheckedException</prop>
<prop key=”update*”>
PROPAGATION_REQUIRED</prop>
<prop key=”*”>
PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
</beans>

The following are the key differences from EJB CMT (from Introduce the Spring Framework)
a. Transaction management can be applied to any POJO. We recommend that business objects implement interfaces, but this is a matter of good programming practice, and is not enforced by the framework.

b. Programmatic rollback can be achieved within a transactional POJO through using the Spring transaction API. We provide static methods for this, using ThreadLocal variables, so you don’t need to propagate a context object such as an EJBContext to ensure rollback.

c. You can define rollback rules declaratively. Whereas EJB will not automatically roll back a transaction on an uncaught application exception (only on unchecked exceptions, other types of Throwable and “system” exceptions), application developers often want a transaction to roll back on any exception. Spring transaction management allows you to specify declaratively which exceptions and subclasses should cause automatic rollback. Default behaviour is as with EJB, but you can specify automatic rollback on checked, as well as unchecked exceptions. This has the important benefit of minimizing the need for programmatic rollback, which creates a dependence on the Spring transaction API (as EJB programmatic rollback does on the EJBContext).

d. Because the underlying Spring transaction abstraction supports savepoints if they are supported by the underlying transaction infrastructure, Spring’s declarative transaction management can support nested transactions, in addition to the propagation modes specified by EJB CMT (which Spring supports with identical semantics to EJB). Thus, for example, if you have doing JDBC operations on Oracle, you can use declarative nested transactions using Spring.

You cannot control the atomicity, consistency, and durability of a transaction, but you can control the transaction propagation and timeout, which set whether the transaction should be read-only and specify the isolation level.

Spring encapsulates all these settings in a TransactionDefinition interface. This interface is used in the core interface of the transaction support in Spring, the PlatfromTransactionManager, whose implementations perform transaction management on a specific platform, such as JDBC or JTA. The core method, PlatformTransactionManager.getTransaction(), returns a TransactionStatus interface, which is used to control the transaction execution, more specifically to set the transaction result and to check whether the transaction is read-only or whether it is a new transaction.

Exploring the TransactionDefinition Interface

As we mentioned earlier, the TransactionDefinition interface controls the properties of a transaction.

package org.springframework.transaction;
import java.sql.Connection;
public interface TransactionDefinition {
int getPropagationBehavior();
int getIsolationLevel();
int getTimeout();
boolean isReadOnly();
}

Using the TransactionStatus Interface

This interface allows a transactional manager to control the transaction execution. The code can check whether the transaction is a new one, or whether it is a read- only transaction and it can initiate a rollback.

public interface TransactionStatus {
boolean isNewTransaction();
void setRollbackOnly();
boolean isRollbackOnly();
}

Implementations of the PlatformTransactionManager

This is an interface that uses the TransactionDefinition and TransactionStatus interfaces to create and manage transactions. The actual implementations of this interface must have detailed knowledge of the transaction manager. The DataSourceTransactionManager controls transactions performed within a DataSource; HibernateTransactionManager controls transactions performed on a Hibernate session, JdoTransactionManager manages JDO transactions, and JtaTransactionManager delegates transaction management to JTA

Configuring Spring’s Transaction Manager for JDBC
To set up transaction management for your applications, you need to configure the transaction
manager of your choice. The simplest way to start is to use the DataSourceTransactionManager. It’s suitable when working with JDBC or iBATIS.

Configuring DataSourceTransactionManagement

<beans>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"/>
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource. DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>

In the most straightforward scenario, DataSourceTransactionManager will obtain a new Connection object from the DataSource object and bind it to the current thread when a
transaction starts. It will remove the Connection object from the current thread when the transaction ends and commit or roll back the active transaction, as necessary, and close the Connection object.
Configuring Spring’s Transaction Manager for JTA
An alternative transaction-management strategy is to use a JTA transaction manager. All application servers come with such a transaction manager, although some stand-alone implementations exist.You don’t automatically need to use JTA when deploying applications in an application server.Nothing stops you from using DataSourceTransactionManager, which gives you the advantage of more independence from the deployment environment.
However, in a minority of cases, you want to delegate transaction management to the JTA
transaction manager of your application server. The most common reason for this is to work with distributed transactions.

Setting Up Transaction Management via JTA in Spring
<beans>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:env/jdbc/myDataSource"/>
</bean>
<bean id="transactionManager" class="org.springframework.jta.JtaTransactionManager"/>
</beans>

When working with the JTA transaction manager of an application server, you must use a
DataSource object that was obtained via JNDI from the same application server. JtaTransactionManager needs no special configuration. This is because the JTA transaction
manager in the application server will automatically start and end the transactions on
Connection objects that were obtained from the JNDI DataSource object.

Bringing Advanced Transaction Capabilities to Spring Applications
This article discusses Spring's transaction management facilities and the common use cases in Spring where an external transaction manager is required. A real-world application is used to illustrate the transactional aspects and features. The focus is on leveraging JTA transaction management in the Spring Framework for enterprise applications. The article shows how Spring's transaction services can seamlessly expose and interact with a Java EE application server's transaction manager such as the Oracle Application Server and the OC4JJtaTransactionManager.

Coming up Next in this series related to "Spring Framework" is, Aspect Oriented Programming(AOP).

Suggested Reading :

http://www.oracle.com/technology/tech/java/spring/jta_spring_article.pdf

http://www.infoq.com/minibooks/JTDS

Pro Spring Book preview

http://dev2dev.bea.com/pub/a/2005/07/spring_transactions.html

http://www.itvcon.com/read/400907_1.htm

Suggested Video Tutorial


Mission Critical Transaction Management using Spring


Friday, January 18, 2008

What makes "Spring Framework" tick,and that too in a big way-Part 1

The most telling aspect or area where Java Developers & for that matter the architects, are heavily tested is developing and designing middleware & server-side components.And I have developed many such kind of applications using EJB in the past.And even though there has been lot of growth from EJB2.1 to EJB3.0 specifications(particularly,annotations),the areas where personally I had a hard time using it has been unit testing the code and implementing effective transaction management.Some might argue ,Iam blaming it because I cant use it effectively and Iam not at all questioning its virtue and value and Iam still and will use it,being a standard framework defined by the Java Community Process (JCP) and supported by all major J2EE vendors,my focus is how best other lightweight solutions like Spring,Hibernate or for that matter Google Guice(even though I didnt get an opportunity to use & implement Guice in any enterprise applications so far),has made my life easier with respect to TDD and implementing Transaction management,security and persistence in distributed computing.

Lightweight vs Heavyweight frameworks

A software framework is a re-usable design for a software system (or subsystem). A software framework may include support programs, code libraries, a scripting language, or other software to help develop and glue together the different components of a software project. Various parts of the framework may be exposed through an API.

Lightweight framework : Applications developed using lightweight framework do not have to depend on framework interfaces or abstract classes to "hook" components into the application in which category frameworks like Spring,Google Guice fall into compared to Heavyweight frameworks ,that require the extension of framework classes or the implementation of framework interfaces in order to take advantage of their middleware features. EJB2 is probably the most popular example of a heavyweight framework(And I do know the growth and support in EJB3 for POJOs,discussed later,which makes it lightweight and starting to become popular because of EJB3 Annotations along with JPA ).EJB is a heavyweight model for objects that don’t need to offer remote access.

Test first development has become much more popular in the last few years, and usually produces impressive results. Writing effective unit tests for an application isn’t just a question of putting in the time and effort; it can be severely constrained by high-level architecture. This is one of the biggest frustrations with EJB. Due to its heavy dependence on the EJB container, business logic coded in EJB is very hard to test.Code that is hard to test is usually also hard to re-engineer, reuse in different contexts, and refactor(though one might argue with me citing the existence of lightweight frameworks like MockEJB)and considering testability is an essential characteristic of agile projects.

Spring Framework
Spring is an open source project led by SpringSource & Interface21 and brainchild of Rod Johnson.Spring is a light-weight framework for the development of enterprise-ready applications. Spring can be used to configure declarative transaction management, remote access to your logic using RMI or web services, mailing facilities and various options in persisting your data to a database. Spring framework can be used in modular fashion, it allows to use in parts and leave the other components which is not required by the application.The Spring framework is a layered architecture consisting of seven well-defined modules.Here is a brief description of the seven modules,

Inversion of Control (IoC) Container: Also called the Core Container, creates and configures application objects and wires them together. This means that resources and collaborating objects are provided to objects, so the objects do not need to look them up. This moves an important responsibility out of your code and makes it easier to write and test code.

Aspect-Oriented Programming (AOP) framework:Works with cross-cutting concerns—one solution to a problem that’s used in multiple places. The Spring AOP framework links cross-cutting concerns to the invocation of specific methods on specific objects (not classes) in such a way
that your code is unaware of their presence. The Spring Framework uses cross-cutting concerns and AOP to let your application deal with transactions without having a single line of transaction management code in your code base.

Data Access framework: Hides the complexity of using persistence APIs such as JDBC,Hibernate, and many others. Spring solves problems that have been haunting data-access developers for years: how to get hold of a database connection, how to make sure that the connection is closed, how to deal with exceptions, and how to do transaction management. When using the Spring Framework, all these issues are taken care of by the framework.

Transaction Management framework: Provides a very efficient way to add transaction management to your applications without affecting your code base. Adding transaction management is a matter of configuration, and it makes the lives of application developers much easier.Spring Framework simplifies it dramatically.And along with Unit Testing,this is the area I would be dwelling upon here.

Resource Abstraction framework: Offers a wonderful feature for conveniently locating files when configuring your applications. Chapter 2 discusses resource abstraction.

Validation framework: Hides the details of validating objects in web applications or rich client applications. It also deals with internationalization (i18n) and localization (l10n).

Spring Web MVC(Another significant framework,one of my fav): Provides a Model-View-Controller (MVC) framework that lets you build powerful web applications with ease. It handles the mapping of requests to controllers and of controllers to views. It has excellent form-handling and form-validation capabilities, and integrates with all popular view technologies, including JSP, Velocity, FreeMarker, XSLT,JasperReports, Excel, and PDFs.

Spring Web Flow:Makes implementing web-based wizards and complex workflow processes very easy and straightforward. Spring Web Flow is a conversation-based MVC framework.Spring Web Flow is distributed separately and can be downloaded via the Spring Framework website.

Acegi Security System: Adds authentication and authorization to objects in your application using AOP. Acegi can secure any web application, even those that do not use the Spring Framework.It offers a wide range of authentication and authorization options that will fit your most exotic security needs. Adding security checks to your application is straightforward and a
matter of configuration; you don’t need to write any code, except in some special use cases.Acegi is distributed separately and can be downloaded from http://acegisecurity.org/downloads.html.

Remote Access framework: Adds client-server capabilities to applications through configuration.Objects on the server can be exported as remotely available services. On the client, you can call these services transparently, also through configuration. Remotely accessing services
over the network thus becomes very easy. Spring’s Remote Access framework supports HTTPbased protocols and remote method invocation (RMI), and can access Enterprise JavaBeans as a client.

Spring Web Services: Takes the complexity out of web services and separates the concerns into manageable units. Most web service frameworks generate web service end points and definitions based on Java classes, which get you going really fast, but become very hard to manage as your project evolves. To solve this problem, Spring Web Services takes a layered approach and
separates the transport from the actual web service implementation by looking at web services as a messaging mechanism. Handling the XML message, executing business logic, and generating an XML response are all separate concerns that can be conveniently managed. Spring Web Services is distributed separately and can be downloaded via the Spring Framework website

Spring JMX: Exports objects via Java Management Extensions (JMX) through configuration.Spring JMX is closely related to Spring’s Remote Access framework. These objects can then be managed via JMX clients to change the value of properties, execute methods, or report statistics.
JMX allows you to reconfigure application objects remotely and without needing to restart the application.

OK lets start exploring the easiness ,robustness & scalability features being supported by Spring in Unit Testing and Transaction Management of the enterprise applications.

Test Driven Development with Spring Framework
To understand its use, we need to know what a POJO(Plain Old Java Object) is,POJO is a Java Object that doesn't implement any special interfaces or call any framework classes,remember the definition of Lightweight Framework.The benefits of POJO comes from decoupling the application code from the infrastructure frameworks.POJOs accelerate development, we can test our business logic outside of the application server(important criteria in TDD) and without a database.We dont have to package the code and deploy it in the application server and also we dont have to keep the database schema constantly in sync with the object model or spend time waiting for slow-running database tests to finish.
The Spring framework,provides services for POJOs such as transaction management,dependency injection,support for POJO remoting and security for POJOs(Acegi).

Dependency Injection
Dependency Injection is one of the core features of Spring Framework.
Dependency injection (DI) refers to the process of supplying an external dependency to a software component and is a specific form of inversion of control where the concern being inverted is the process of obtaining the needed dependency.

Conventionally, if an object needs to gain access to a particular service, the object takes responsibility to get hold of that service: either it holds a direct reference to the location of that service, or it goes to a known 'service locator' (in EJB2)and requests that it be passed back a reference to an implementation of a specified type of service. By contrast, using dependency injection, the object simply provides a property that can hold a reference to that type of service; and when the object is created a reference to an implementation of that type of service will automatically be injected into that property - by an external mechanism. The dependency injection approach offers more flexibility because it becomes easier to create alternative implementations of a given service type, and then to specify which implementation is to be used via a configuration file, without any change to the objects that use the service. This is especially useful in unit testing, because it is easy to inject a mock implementation of a service into the object being tested. On the other hand, excessive use of dependency injection can make applications more complex and harder to maintain: in order to understand the application's behaviour the developer needs to look at the configuration as well as the code, and the configuration is "invisible" to IDE-supported reference analysis and refactoring unless the IDE specifically supports the dependency injection framework.To use it,you must configure Spring's bean factory

Benefits of Dependency Injection


It eliminates the need to call lookup APIs,because a components dependencies are passed to it,we no longer have to write tedious JNDI code and components depend mainly on interfaces rather than on concrete implementations.

Types of dependency injection
Constructor injection,setter&getter injection and Method injection.

Spring’s org.springframework.test package has
number of base classes to simplify testing.
AbstractDependencyInjectionSpringContextTests - can do both setter or field-based dependency injection,cached context files
AbstractTransactionalDataSourceSpringContextTests -
allows you to easily clear data from tables and rolls back any data entered into the database.

Testing approaches
Generally speaking, testing should be used to ensure the following aspects of an application:
Correctness: You want to ensure the correctness of your application. For example, suppose that you have written a calculate() method on a Calculator class. You want to make sure that certain input for this method results in a correct calculation result.
Completeness: Testing can be used to ensure that your application is complete by verifying that all required operations have been executed. Suppose you have a signup process that includes creating an invoice for newly signed-up members. You want to test whether a member is actually added to the database, and also if an invoice has been created for that user.
Quality: Testing can ensure the quality of your application, and this goes beyond software quality metrics. A well-tested piece of software creates confidence with developers. When existing code needs to be changed, it’s less likely that developers will be afraid of unintentionally
breaking the software or reintroducing bugs.

Unit Testing
This so-called plain old Java object (POJO) approach to Java coding, combined with defining interfaces for important parts of your application provides the basis for thorough testing. The Spring Framework promotes exactly this approach (we could also say the Spring Framework makes this approach possible). By separating your code into well-defined interfaces and objects, you have already defined the units that are eligible for unit testing.
One goal of unit testing is to ensure that each unit of an application functions correctly in isolation.Another goal is to define a framework, harness, or contract (all referring to a strict set of rules that must be respected) that must be satisfied by the unit test. As long as the tests can be run successfully,
the unit is considered to work properly. (If there are bugs in the test code, the unit will function properly according to this buggy test code.)

Unit testing offers a number of benefits for developers:
Facilitate change: As previously mentioned, having a set of unit tests for a specific piece of code provides confidence in refactoring existing code. The unit tests will ensure the module continues to function correctly according to the available tests as long as the tests succeed.
Given there are enough tests for all the code in the application, this promotes and facilitates changing implementation details of units in the application. An important aspect of facilitating change is preventing solved problems or bugs from reentering the code.
Simplify integration: Unit testing provides a bottom-up testing approach, which ensures that low-level units function properly according to their tests. This makes it easier to write integration tests at a later stage. There is no need to have two tests for units.
Promote well-defined separation: In order for you to be able to completely and efficiently write unit tests, your code needs to be separated into well-defined units. Each unit needs to be tested in isolation and should therefore allow the replacement of dependencies with test specific ones. Thus, writing unit tests promotes the separation of your application into well-defined units.

Test-driven development (TDD) is a way of implementing code by writing a unit test before implementing the actual class.
Using Spring for Testing
When working with Spring for building your applications, you will typically use one or more XML configuration files for defining your application context. These configuration files are not Java files and will therefore not be compiled. Of course, if you include the Spring DTD or use Spring’s namespace support, some aspects of your configuration files will be validated. But issues such as defining a nonexisting class as the class for a bean in your application context or setting a nonexisting property on a bean definition are discovered only when you actually load the application context at runtime. This is where integration testing comes into the picture.The goal of integration testing is to test how the individually tested units of your application collaborate with each other. When working with Spring, you wire those dependencies together using Spring’s configuration files. In order to test part of your whole application, you typically want to load the Spring application context and test one or more beans configured in that application.

Spring provides three convenient test base classes for integration testing of your Spring applications: AbstractDependencyInjectionSpringContextTests, AbstractTransactionalSpringContextTests, and AbstractTransactionalDataSourceSpringContextTests. These classes are discussed in the following sections.

The org.springframework.test.AbstractDependencyInjectionSpringContextTests base class is the test class you will typically use when testing parts of your application that do not require access to a database or any other transactional support. You should extend this class by first implementing the getConfigLocations() method, which should return an array of application context locations to be loaded by the test. When the test is executed, the specified configurations will be loaded as an application context.
The major advantage of using this base class is that the application context will be loaded only once for each test method. If you were to load the application yourself in the setUp() method of a test, the application context would be reloaded for every test method. This is especially useful when loading configurations that require a lot of initialization, such as a Hibernate session factory.

Another convenient test base class is org.springframework.test.AbstractTransactionalSpringContextTests, which builds on top of the functionality offered by the AbstractDependencyInjectionSpringContextTests test base class. Each test method that is executed by a subclass of this base class will automatically participate in a transaction. Because the default is to roll back
the transaction after each test method execution, no actual modifications will be made to any transactional resources. This makes it the perfect choice for performing integration tests using a transactional data source.
Using this base class allows you to integration test functionality that will make modifications to the database without having to worry about the changes affecting any other test methods. It also allows you test code that requires a transactional context. And you can write data to the database without worrying about cleaning it up afterwards.As mentioned, all modifications to the database are rolled back at the end of each test method execution.

A third convenient test base class is org.springframework.test.AbstractTransactionalDataSourceSpringContextTests, which builds on top of the functionality provided by AbstractTransactional
SpringContextTests. In order to use this base class, you need to include a DataSource definition in the application context loaded by this test. The data source is automatically injected, as explained earlier.
The main feature offered by this base class is that it provides you with a JdbcTemplate as a protected field, which you can use to modify the data source, within the transactional context. You could, for instance, insert some data that the test needs in order to succeed. Because the statements to the JdbcTemplate are also executed within the transactional context, you do not need to worry about cleaning up the database or modifying the existing data.Another advantage of using this base class is that you can define fields for this test that are populated
automatically by Spring based on your application context.Spring also provides support for testing your J2EE-specific application code. Because much of your web application code is very much tied to J2EE classes, it is hard to test. For instance, testing a servlet or a Spring controller implementation requires you to somehow mock the HttpServletRequest and HttpServletResponse classes.

Transaction Management using Spring
Two main issues make database transactions complicated for developers to work with and difficult for database vendors to implement:
Concurrency control: Databases need to protect against data loss or ghost data, yet allow concurrent access to the same data. Generally, developers can choose an isolation level to control the level of protection. Another form of concurrency control is protecting against lost updates.

Synchronization between transactions: Complex applications often need a way to synchronize two or more databases or other resources so that their local transactions are guaranteed to commit or roll back in a group. The technique used for this is called two-phase commit (or 2PC), distributed transactions, or global transactions.
The first step in setting up transaction management with Spring is choosing a transaction management strategy. This basically means selecting which of the transaction-management APIs in Java you want to use.The main interface of this API is org.springframework.transaction.PlatformTransactionManager.
Spring provides a number of implementations of this interface that support the most popular transaction-management APIs in Java.Like,org.springframework.jdbc.datasource. DataSourceTransactionManager,org.springframework.orm.hibernate.HibernateTransactionManager
org.springframework.orm.hibernate3.HibernateTransactionManager.
The Spring Bean factory does more than simply instantiate objects.It can also wrap the objects that it creates with interceptors.These interceptors are how Spring provides a simple,yet effective AOP(Aspect-Oriented Programming)implementation.AOP is the foundation of Spring Transaction Management.To make a POJO transactional you configure the bean factory to wrap it with TransactionInterceptor.One option is to use the @Transactional annotation on the interace,implementation class or individual methods.Another option is to write XML bean definitions that explicitly apply the TransactionInterceptor to the POJO.The XML is more verbose than the annotation but has the advantage of leaving the source code unchanged.It also works with older JDKs that dont' support annotations.

Spring doesn't implement transactions itself but is,instead, a wrapper around other transaction management APIs.Unlike EJB3,it gives you the flexibility of using either JTA or the transaction management APIs provided by ORM frameworks such as Hibernate.

In the next article of this series,we will explore more about Transaction Management in Spring and as well as AOP(Aspect Oriented Programming).

Suggested Video Tutorial

Spring 2.x by Rod Johnson (Founder of Spring framework)

Integration Testing with Spring by Rod Johnson

Spring vs EJB3.0 by Debu Panda


Spring Experience Video by Adrian Colyer
Adrian Colyer is the leader of the AspectJ open source project and a well-known industry expert on the topic of aspect-oriented programming (AOP)



Suggested Reading:


http://java.sys-con.com/read/180374.htm


http://static.springframework.org/spring/docs/2.5.1/reference/testing.html



http://static.springframework.org/spring/docs/1.2.x/reference/transaction.html



http://mike.hostetlerhome.com/2007/07/06/easier-unit-testing-in-spring/



http://dev2dev.bea.com/pub/a/2005/07/spring_transactions.html


Recommended Books



You can get this book from Here

Friday, January 4, 2008

Guide to Spring 2.0

Here is the definitive guide to Springv2.0,one of my fav open source frameworks.

Spring vs Google Guice

I 've happened to come across this open source Dependency Injection solution from Google and I read Guice user guide and it states that using Guice you get dependency injection without the tedious XML config files.
I agree, the Spring XML config files are more verbose than a configuration need be.
However, I think the Guice comparison leaves out a few, central points in the comparison.
These are:

1) Guice uses annotations to mark injection points.

2) Guice doesn't do third party component injection. You need to implement a custom provider for this.
This is mentioned too quickly in the comparison, as if it didn't matter.
3) Guice doesn't help you with component / application configuration.

4) Component injection configuration is spread throughout the application.

5) Guice should have been compared to Pico Container, which also uses a Java API for configuration.

Guice uses the @Inject annotation to mark where to inject values. Using annotations to mark this is, in my opinion, a less-than-optimal mechanism. It will work for most cases, but it is kinda static. If you have not marked a dependency in a constructor or method for injection with an @Inject,annotation, you can't have it injected. So what happens if you want different configurations of the same component? One instance where you inject 2 values, and one instance where you inject 4? How do you tell to Guice what dependencies to ignore, or add, compared to the ones
marked with the class static annotations? Yes, using named annotations you can determine *what* configuration to inject, but can you also control how many to inject?

The @Inject annotation also results in Guice being unable to inject dependencies into third party components. If the code doesn't have the @Inject annotation, Guice can't inject into it. You can work around this by writing custom providers, Bob Lee writes. But this forces me to use a second mechanism for third party components. Spring doesn't.

Springs XML files can glue all kinds of components together. It can also be used to
inject configuration parameters into components. Configuration parameters like database driver, url, user and password, or like directories on hard drives, server addresses etc.
Is this easy to do with Guice? I'd have to register some String instances with named annotations,and specify where to inject them using @Inject annotations, right? And what about injecting these configuration values into a third party component? Springs XML files does all that exactly the same way you inject one of your classes into another.

Another aspect I think is missing is that when using Guice the injection configuration is spread throughout the application. Some is marked on components with the @Inject annotation.
Some is marked in Guice modules. Some is implemented in custom providers. And yet some is specified on the interfaces using an @ImplementedBy annotation. In Spring you know where to look. In the XML files. This is a speculated "problem". It may turn out to be no problem at all in practice

And while looking for more deeper insights into it, I came across this beautiful article William Slouth's Code where William has given a very good example which shows how Guice increases the performance of an application.
For now I would like to analyze this more,before saying it is better than Spring.
Suggested Video Tutorial



I would like someone else to shed more light on this........

Wednesday, June 6, 2007

Spring vs EJB3

Iam posting this topic since I have experienced this topic being raised during one of my technological architectural level discussions I had with my collegue and basically he was supporting EJB3 and me,Spring...And I leave it to you guys who are ready to post their own comments and reason out with pros and cons which technology is better to use in mission critical enterprise level J2EE applications and share your experience and thoughts.........

For now Iam directing you to this link and if you have any other resources/stuff do post in here........

SPRING V/S EJB3